/**
 * fs 模块的promise包装
 * @author LiQun
 * @date 2019-07-27
 */
const fs = require('fs');
const {basename, extname} = require('path')
module.exports = {
  /**
   * 读取文件
   * @author LiQun
   * @date 2019-07-27
   * @param path 文件路径
   * @param options 可选参数
   */
  readFile(path, options = {}) {
    return new Promise((resolve, reject) => {
      fs.readFile(path, Object.assign({}, {flag: 'r+', encoding: 'utf-8'}, options), (err, data) => {
        if (!!err) reject(err);
        resolve(data);
      })
    })
  },
  /**
   * 写文件promise方法
   * @author LiQun
   * @date 2019-07-27
   */
  writeFile(path, data, options = {}) {
    return new Promise((resolve, reject) => {
      fs.writeFile(path, data, Object.assign({}, {flag: 'w', encoding: 'utf-8', mode: '0666'}, options), (err) => {
        if (!!err) reject(err);
        resolve();
      })
    })
  },
  /**
   * 追加内容到文件中
   * @author LiQun
   * @date 2019-07-27
   */
  appendFile(path, data, options) {
    return new Promise((resolve, reject) => {
      fs.appendFile(path, data, Object.assign({}, {encoding: 'utf-8'}, options), (err) => {
        if (!!err) reject(err);
        resolve();
      })
    })
  },
  isFile(filePath) {
    fs.statSync();
  },
  isDirectory(filePath) {

  },
  getFileProps(filePath) {
    const stat = fs.statSync(filePath);
    const filename = filePath.substring(filePath.lastIndexOf('/') + 1);
    const fileInfo = {
      filename: basename(filename),
      size: stat.size,
      fullPath: filePath,
      dir: filePath,
      extname: extname(filename)
    }
    return fileInfo;
  },
  getChildren: function (filePath) {
    if (!filePath) {
      throw new Error('请传入文件路径')
    }
    const ret = [];
    // 如果传入的是文件,则直接返回该文件信息
    const stat = fs.statSync(filePath);
    if (stat.isFile()) {
      return [this.getFileProps(filePath)];
    }
    const that = this;

    function getSubFiles(filePath) {
      // const stat = fs.statSync(filePath);
      // if (stat.isDirectory()) {
      //   let files = fs.readdirSync(filePath);
      //   files.forEach((file) => {
      //     getSubFiles(filePath + '/' + file);
      //   })
      // } else {
      //   // 如果是文件,则直接返回
      //   const fileInfo = that.getFileProps(filePath, stat);
      //   ret.push(fileInfo);
      // }
      let files = fs.readdirSync(filePath);
      files.forEach((file) => {
        const fullPath = `${filePath}/${file}`;
        if (fs.existsSync(fullPath)) {
          const stat = fs.statSync(fullPath);
          if (stat.isDirectory()) {
            getSubFiles(fullPath);
          } else {
            // 如果是文件,则直接返回
            const fileInfo = that.getFileProps(fullPath);
            ret.push(fileInfo);
          }
        }
      })
    }

    getSubFiles(filePath);
    return ret;
  },
};


